package com.jacky.ws.config;

import com.jacky.ws.properties.RedissonProperties;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {

    private final RedissonProperties conf;

    public RedissonConfig(RedissonProperties conf) {
        this.conf = conf;
    }

    @Bean(name = "redissonClient", destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.setCodec(new StringCodec());
        if (conf.getSentinelAddresses() != null && conf.getSentinelAddresses().length > 0) {
            config.useSentinelServers()
                    .setMasterName(conf.getMasterName())
                    .addSentinelAddress(conf.getSentinelAddresses())
                    .setPassword(conf.getPassword())
                    .setDatabase(conf.getDatabase());
        } else {
            SingleServerConfig ssc = config.useSingleServer()
                    .setAddress(conf.getAddress())
                    .setTimeout(conf.getTimeout())
                    .setConnectionPoolSize(conf.getConnectionPoolSize())
                    .setConnectionMinimumIdleSize(conf.getConnectionMinimumIdleSize())
                    .setDatabase(conf.getDatabase());
            if (StringUtils.isNotBlank(conf.getPassword())) {
                ssc.setPassword(conf.getPassword());
            }
        }
        return Redisson.create(config);
    }
}
